package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseDelegateMultiAdapter;
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.ChoiceExam;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class MyChoiceExamActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.btn_create_choice_exam)
    AppCompatButton mBtnCreateChoiceExam;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    private int mPage = 1;
    private static final int PAGE_SIZE = 10;

    private ChoiceExamAdapter mExamAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRefreshLayout.autoRefresh();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_choice_exam;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mBtnCreateChoiceExam.setEnabled(true);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mExamAdapter = new ChoiceExamAdapter();
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mExamAdapter.setEmptyView(emptyView);
        mRecyclerView.setAdapter(mExamAdapter);
        int divider = DisplayUtil.dip2px(16f);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(0, 0, 0, 0);
                } else {
                    outRect.set(0, divider, 0, 0);
                }
            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.my_choice_exam;
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, MyChoiceExamActivity.class);
        context.startActivity(intent);
    }

    @OnClick(R.id.btn_create_choice_exam)
    public void onViewClicked() {
        CreateChoiceExamActivity.actionStart(getContext());
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getChoiceExamList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getChoiceExamList();
    }

    private void getChoiceExamList() {
        addDisposable(RetrofitService.getNetService()
                .getChoiceExamList(mPage, PAGE_SIZE, 1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                        mRefreshLayout.finishRefresh();
                    if (mRefreshLayout != null && mRefreshLayout.isLoading())
                        mRefreshLayout.finishLoadMore(1000);
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (mPage == 1) {
                            mExamAdapter.setList(response.getData().getList());
                        } else {
                            List<ChoiceExam> examList = response.getData().getList();
                            if (examList != null && examList.size() > 0) {
                                mExamAdapter.addData(examList);
                            } else {
                                mPage--;
                            }
                        }
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                        mRefreshLayout.finishRefresh();
                    if (mRefreshLayout != null && mRefreshLayout.isLoading())
                        mRefreshLayout.finishLoadMore(1000);
                }));
    }

    public class ChoiceExamAdapter extends BaseDelegateMultiAdapter<ChoiceExam, BaseViewHolder> {

        ChoiceExamAdapter() {
            setMultiTypeDelegate(new BaseMultiTypeDelegate<ChoiceExam>() {
                @Override
                public int getItemType(@NotNull List<? extends ChoiceExam> list, int i) {
                    ChoiceExam choiceExam = list.get(i);
                    // 0未发布 1已发布 2未开始 3进行中 4已结束
                    if (choiceExam.getExamStatus() == 0) {
                        return 0;
                    } else if (choiceExam.getExamStatus() == 2 || choiceExam.getExamStatus() == 3) {
                        return 1;
                    } else if (choiceExam.getExamStatus() == 4) {
                        return 2;
                    }
                    return 0;
                }
            });
            assert getMultiTypeDelegate() != null;
            getMultiTypeDelegate().addItemType(0, R.layout.item_list_choice_exam_un_publish);
            getMultiTypeDelegate().addItemType(1, R.layout.item_list_choice_exam_going);
            getMultiTypeDelegate().addItemType(2, R.layout.item_list_choice_exam_finished);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, ChoiceExam choiceExam) {
            baseViewHolder.setText(R.id.tv_name, choiceExam.getExamName())
                    .setText(R.id.tv_state, choiceExam.getExamStatusName())
                    .setText(R.id.tv_time, choiceExam.getStartTime() + " - " + choiceExam.getEndTime())
                    .setText(R.id.tv_question_count, choiceExam.getQuestionCount() + "题目")
                    .setText(R.id.tv_total_score, "总分" + choiceExam.getTotalScore() + "分");
            if (baseViewHolder.getItemViewType() == 0) {
                View tv_view_details = baseViewHolder.getView(R.id.tv_view_details);
                tv_view_details.setTag(choiceExam);
                tv_view_details.setOnClickListener(mOnClickListener);
                View tv_publish = baseViewHolder.getView(R.id.tv_publish);
                tv_publish.setTag(choiceExam);
                tv_publish.setOnClickListener(mOnClickListener);
            } else if (baseViewHolder.getItemViewType() == 1) {
                View tv_view_details = baseViewHolder.getView(R.id.tv_view_details);
                tv_view_details.setTag(choiceExam);
                tv_view_details.setOnClickListener(mOnClickListener);
                View tv_qr_code = baseViewHolder.getView(R.id.tv_qr_code);
                tv_qr_code.setTag(choiceExam);
                tv_qr_code.setOnClickListener(mOnClickListener);
                View tv_statistics = baseViewHolder.getView(R.id.tv_statistics);
                tv_statistics.setTag(choiceExam);
                tv_statistics.setOnClickListener(mOnClickListener);
            } else if (baseViewHolder.getItemViewType() == 2) {
                View tv_view_details = baseViewHolder.getView(R.id.tv_view_details);
                tv_view_details.setTag(choiceExam);
                tv_view_details.setOnClickListener(mOnClickListener);
                View tv_statistics = baseViewHolder.getView(R.id.tv_statistics);
                tv_statistics.setTag(choiceExam);
                tv_statistics.setOnClickListener(mOnClickListener);
            }
        }
    }

    private View.OnClickListener mOnClickListener = v -> {
        ChoiceExam choiceExam = (ChoiceExam) v.getTag();
        switch (v.getId()) {
            case R.id.tv_view_details: {// 查看详情
                if (choiceExam != null) {
                    ViewExamDetailsActivity.actionStart(getContext(), choiceExam.getExamId());
                }
            }
            break;
            case R.id.tv_qr_code: {// 考试二维码
                if (choiceExam != null) {
                    ChoiceExamPublishSuccessActivity.actionStart(
                            getContext(), choiceExam.getExamId(), choiceExam.getExamName(),
                            choiceExam.getStartTime(), choiceExam.getEndTime());
                }
            }
            break;
            case R.id.tv_statistics: {// 学习统计
                if (choiceExam != null) {
                    Intent intent = new Intent(getContext(), StudyStatisticsActivity.class);
                    intent.putExtra("examId", choiceExam.getExamId());
                    startActivity(intent);
                }
            }
            break;
            case R.id.tv_publish: {// 发布

            }
            break;
        }
    };
}
